package com.codered;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import javax.net.ssl.HttpsURLConnection;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.util.Log;

public class UploadService extends Service {

	/**
	 * Variables
	 */
	
	// Constants
	protected static final String TAG = "UploadService";
	protected static final boolean DEBUG = true;

	protected final String lineEnd = "\r\n";
	protected final String twoHyphens = "--";
	protected final String boundary = "*****";
	
	
	
	
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate() {
        if (DEBUG) Log.i(TAG, "-----onCreate fired-----");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	if (DEBUG) Log.i(TAG, "-----onStart fired-----");
    	
        String[] filelist = fileList();
        if (DEBUG) Log.i(TAG, "Filename: " + Arrays.toString(filelist));
        if (filelist.length > 0) {
        	uploadFiles(filelist);
        }

    	stopSelf(startId);
    	
    	return START_NOT_STICKY;
    }
    
    @Override
	public IBinder onBind(Intent arg0) {
    	if (DEBUG) Log.i(TAG, "-----onBind fired-----");
		// TODO Auto-generated method stub
		return null;
	}
    
    @Override
    public void onDestroy() {
    	if (DEBUG) Log.i(TAG, "-----onDestroy fired-----");
    }
    

    
    
    
    
    
    protected void uploadFiles(String[] fileList) {
    	for (String file : fileList) {
    		uploadFile(file);
    	}
    }
    
    protected void uploadFile(String file) {
    	
    	// TODO: Improve thread usage
    	/*
    	new Thread(new Runnable() {
            public void run() {
                final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
                mImageView.post(new Runnable() {
                    public void run() {
                        mImageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
        */
    	final String filePath = file;
    	new Thread(new Runnable() {
    		public void run() {
    			
    	    	try {
    	            URL url = new URL("https://dconstructing.com/");
    	            if (DEBUG) Log.i(TAG, "URL: "+url);
    	            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    	            if (DEBUG) Log.i(TAG, "Connection made");
    	            try {
    	            	conn.setDoOutput(true); // going to be a POST
    	            	conn.setChunkedStreamingMode(0); // 0 = system default chunk size
    	            	conn.setRequestMethod("POST");
    					conn.setRequestProperty("Connection", "Keep-Alive");
    					conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
    	            	
    	            	//OutputStream out = new BufferedOutputStream(conn.getOutputStream());
    	            	//writeStream(out, file);
    	            	
    					Log.i(TAG, "getting Data Stream");
    	            	DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    	            	Log.i(TAG, "Data Stream gotten");
    	            	writeStream(dos, filePath);
    	            	Log.i(TAG, "Data Stream written");
    					
    	            	/*
    	            	InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    	            	if (!url.getHost().equals(urlConnection.getURL().getHost())) {
    	            	}
    	            	readStream(in);
    	            	*/
    	            } finally {
    	            	conn.disconnect();
    	            }
    			} catch (MalformedURLException e) {
    				if (DEBUG) Log.e(TAG, "Malformed URL", e);
    			} catch (IOException e) {
    				if (DEBUG) Log.e(TAG, "I/O Exception 1", e);
    			} finally {
    			}
    		}
    	}).start();
    	
    }
    
    protected void writeStream(DataOutputStream dos, String file) {
    	try {
    		FileInputStream fileInputStream = new FileInputStream(file);
    		
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + file +"\"" + lineEnd);
			dos.writeBytes(lineEnd);
			
			// create a buffer of maximum size
			int bytesAvailable = fileInputStream.available();
			int maxBufferSize = 1024;
			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
			byte[] buffer = new byte[bufferSize];
			
			// read file and write it into form...
			int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			
			while (bytesRead > 0)
			{
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}
			
			// send multipart form data after file data...
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
			// close streams
			fileInputStream.close();
			dos.flush();
    		
    	} catch (FileNotFoundException e) {
    		if (DEBUG) Log.i(TAG, "File was not found: "+file);
    	} catch (IOException e) {
    		if (DEBUG) Log.i(TAG, "I/O Exception 2");
    	}
    }
    
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
    }

}
